package com.eurasia.assignment.service;

import com.eurasia.assignment.security.JwtTokenUtil;
import com.eurasia.assignment.service.port.out.FetchHOJAuthorizationPort;
import com.eurasia.assignment.service.port.out.HOJAuthToken;
import com.eurasia.assignment.service.port.out.AccessHOJAuthorizationPort;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
@Log4j2
public class HOJAuthTokenService {
    private final FetchHOJAuthorizationPort fetchHOJAuthorizationPort;
    private final AccessHOJAuthorizationPort accessHOJAuthorizationPort;
    private final JwtTokenUtil jwtTokenUtil;

    public HOJAuthToken refreshHOJAuthToken() {
        HOJAuthToken authorization;
        try {
            String token = fetchHOJAuthorizationPort.fetchHOJAuthorization();
            LocalDateTime expirationDate = jwtTokenUtil.getExpirationDateFromToken(token);

            authorization = HOJAuthToken.builder()
                    .token(token)
                    .createTime(LocalDateTime.now())
                    .expiresTime(expirationDate)
                    .success(true)
                    .build();
        } catch (Exception e) {
            authorization = HOJAuthToken.builder()
                    .success(false)
                    .token("INVALID_TOKEN")
                    .message(e.getMessage())
                    .build();

            e.printStackTrace();
            log.debug("获取HOJ授权失败: {}", e.getMessage());
        }

        return accessHOJAuthorizationPort.save(authorization);
    }
}
